import { Component } from '@angular/core';
import { NzFormatEmitEvent } from 'ng-zorro-antd';

declare var form: any;

@Component({
  selector: 'app-ui-userrole',
  templateUrl: './user.role.component.html',
  styleUrls: ['./user.role.component.scss']
})
export class UserRoleComponent {
  foreignValue: string;
  isVisible = false;
  roleID: string;
  roleName: string;
  searchRole: string;

  fs: any = null;
  depDic: any = null;

  constructor() {
    this.fs = new form.FormSimpleService('userinfo', {
      keyField: 'userid',
      randomFields: ['userid'],
      orderObject: { userid: 0 }
    });
    this.depDic = new form.DictionaryService('dic_department');
    this.depDic.load('0');
  }

  query() {
    delete this.fs.queryObject['roles:like'];
    delete this.fs.queryObject['roles:notlike'];
    if (this.searchRole === '1') {
      // 非当前角色
      this.fs.queryObject['roles:notlike'] = this.roleID;
    } else if (this.searchRole === '2') {
      // 当前角色
      this.fs.queryObject['roles:like'] = this.roleID;
    }
    const ower = this;
    this.fs.loadData(true, (d) => {
      ower.selectUser(ower, d);
    });
  }

  reset() {
    delete this.fs.queryObject['roles:like'];
    delete this.fs.queryObject['roles:notlike'];
    this.searchRole = '';
    this.fs.resetQueryObject();
    const ower = this;
    this.fs.loadData(true, (d) => {
      ower.selectUser(ower, d);
    });
  }

  open(roleID, roleName) {
    this.isVisible = true;
    this.roleID = roleID;
    this.roleName = roleName;
    this.searchRole = '';

    this.fs.resetQueryObject();
    const ower = this;
    this.fs.loadData(true, (d) => {
      ower.selectUser(ower, d);
    });
  }

  close() {
    this.isVisible = false;
  }

  treeSelect(e) {
    const ower = this;
    this.fs.queryObject['departmentId:like'] = ',' + e.node.key + ',';
    this.fs.loadData(true, (d) => {
      ower.selectUser(ower, d);
    });
    this.filter(e);
  }

  // 根据机构，过滤部门等字典
  private filter(event: Required<NzFormatEmitEvent>) {
    const ower = this;
    ower.foreignValue = event.node.key;
    this.depDic.filter((e) => {
      if (e.other.organizationId === ower.foreignValue) {
        return true;
      } else {
        return false;
      }
    });
  }

  loadDate(re = false) {
    const ower = this;
    this.fs.loadData((d) => {
      ower.selectUser(ower, d);
    }, re);
  }

  selectUser(ower, d) {
    d.forEach(item => {
      if (item.roles.indexOf(ower.roleID) >= 0) {
        item.checked = true;
      }
    });
  }

  update(user) {
    this.fs.editRow(user);
    const row = this.fs.er;
    if (user.checked === true) {
      const i = row.roles.indexOf(this.roleID);
      if (i < 0) {
        row.roles.push(this.roleID);
        this.fs.save();
      }
    } else {
      const i = row.roles.indexOf(this.roleID);
      if (i >= 0) {
        row.roles.splice(i, 1);
        this.fs.save();
      }
    }
  }
}
